# koroFileHeader at Yungoal acer
# Create: 2022-10-14 15:41:17
# LastEdit: 2022-10-14 16:04:13
"""验证性的功能"""
__author__ = '749B'

import json

from django.db.models import Sum
from django.db.models.functions import ExtractYear, ExtractMonth
from django.shortcuts import render

from pyecharts.charts import Bar, Line
from pyecharts import options as opts

from .. import models
from .restapi import JsonResponse

def compare(request):
    return render(request, "billing/compare.html")

def compare_monthly(request):
    company_name = models.Account.objects.values_list('name', flat=True).first()
    rows = models.Summary.objects.all()
    qs = models.Detail.objects.annotate(year=ExtractYear('date'), month=ExtractMonth('date'))\
        .values('year', 'month').annotate(cost=Sum('extended_cost'))
    qs_dict = { f"{i['year']}-{i['month']:0>2d}": i['cost'] for i in qs }

    bar = Bar()
    report_month_list = [ str(row) for row in rows ]
    bar.add_xaxis(report_month_list)
    bar.add_yaxis(
        "Summary", 
        [ i.total_usage for i in rows ], 
        label_opts=opts.LabelOpts(is_show=False), 
        is_selected=False
        )
    bar.add_yaxis(
        "DetailSum", 
        [ qs_dict.get(m) for m in report_month_list ], 
        label_opts=opts.LabelOpts(is_show=False), 
        is_selected=False
        )
    bar.extend_axis(yaxis=opts.AxisOpts(name="误差值",min_=-5, max_=5))
    bar.set_global_opts(title_opts=opts.TitleOpts(title="费用校验", subtitle=company_name))
    bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    line = Line()
    line.add_xaxis(report_month_list)
    line.add_yaxis(
        '误差', 
        [ f'{float(i[0]) - i[1]:.2f}' for i in zip([ i.total_usage for i in rows ], [ qs_dict.get(m) for m in report_month_list ])], 
        yaxis_index=1)
    bar.overlap(line)
    c = bar.dump_options_with_quotes()
    return JsonResponse(json.loads(c))    


